#include "Animation.h"
#include "GraphicalElement.h"
#include "EventWrapper.h"
#include "AnimationDoneInternalEvent.h"

Animation::Animation(unsigned long duration)
        : element(NULL), duration(duration), time(0), doneDestinationId(-1)
{
}

Animation::~Animation()
{
}

void Animation::animate(unsigned long tick)
{
    time += tick;
    double factor = time / (double)duration;

    if (duration == 0)
    {
        update(time);
    }
    else
    {
        update(factor);
    }

    if (duration > 0 && factor > 1.0)
    {
        EventWrapper::push(new AnimationDoneInternalEvent(doneDestinationId));
    }
}

void Animation::render(const Position& parent)
{
    if (element->getTexture() != NULL)
    {
        element->getTexture()->render(parent.move(element->getPosition()));
    }
}

bool Animation::done()
{
    if (duration == 0)
    {
        return false;
    }
    return time > duration;
}

void Animation::setElement(GraphicalElement* element)
{
    this->element = element;
}

void Animation::init()
{
}

void Animation::setDoneDestinationId(long id)
{
    doneDestinationId = id;
}
